package com.qf.listener;

import com.qf.pojo.*;
import com.qf.service.CartService;
import com.qf.service.GoodsService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.utils.SYS;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

import javax.servlet.http.*;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

//@WebListener
public class LogInListener implements HttpSessionListener, HttpSessionAttributeListener {

    private CartService cartService = new CartServiceImpl();
    private GoodsService goodsService=new GoodsServiceImpl();

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("attribute添加了");

        String name=event.getName();
        HttpSession session = event.getSession();

        if(SYS.USER.equals(name)){
            Object obj = session.getAttribute(SYS.USER);
            User user = (User) obj;
            List<Cart> carts=cartService.loadCart(user.getId());
            ShopCart shopCart=new ShopCart();
            for(Cart cart:carts){
                Goods goods=goodsService.getDetailById(cart.getGid());



                shopCart.add(cart.getNum(),goods);

            }
            session.setAttribute(SYS.CART,shopCart);
            System.out.println("get out cart from mysql"+new Date().getTime());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("attributeAdded");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {


    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {


        /*HttpSession session=req.getSession();
        session.setAttribute(SYS.CART,shopCart);*/

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session ended");

        HttpSession session = se.getSession();
        Object obj = session.getAttribute(SYS.CART);
        Object obj2 = session.getAttribute(SYS.USER);
        if (obj != null && obj instanceof ShopCart && obj2 != null && obj2 instanceof User) {
            ShopCart shopCart = (ShopCart) obj;
            User user = (User) obj2;

            Collection<ShopItem> items = shopCart.show();

            for (ShopItem item : items) {
                Goods goods = item.getGoods();
                Cart cart = new Cart(null,user.getId(), goods.getId(), goods.getName(), goods.getPrice(), item.getNum());
                //Integer cartid, Integer uid, Integer gid, String gname, float price, Integer num
                //判断已有的还是新增的
                if(cartService.cartExist(user.getId(),goods.getId())==null){
                    cartService.saveCart(cart);
                } else {
                    cartService.updateCart(user.getId(),goods.getId(),item.getNum());
                }
            }
        }
    }
}
